/**
 * Project: topdt-jbpm
 * Copyright 2013  Top Digital Technology  Co. Ltd.
 * All right reserved.
 */
package com.topdt.jbpm.service;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.thx.common.service.BaseManager;
import com.thx.common.spring.BeanFactory;
import com.topdt.jbpm.dao.ApplicationDao;
import com.topdt.jbpm.dao.FormDao;
import com.topdt.jbpm.form.FormHandle;
import com.topdt.jbpm.form.FormUI;
import com.topdt.jbpm.model.AppHandle;
import com.topdt.jbpm.model.Application;
import com.topdt.jbpm.model.Control;
import com.topdt.jbpm.model.Field;
import com.topdt.jbpm.model.Form;
import com.topdt.jbpm.utils.ObjectUtils;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 建立日期 : 2013-4-25 下午12:00:29<br>
 * 作者 : balance<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
@Service
@Transactional(readOnly = true)
public class FormService extends BaseManager<Form>{
	
	@Autowired
	private FormDao formDao;
	@Autowired
	private ApplicationDao appDao;
	
	//--通过fieldControl 和字段的序号 得到readonly的值
	private static boolean getReadValue(String fieldControl,int turn ){
		boolean result = true;
		char flag = fieldControl.charAt(turn);
		
		switch (flag) {
		case 'R': result=false;
			      break;
		default:
			break;
		}
		return result;
	}
	//--通过fieldControl 和字段的序号 得到display的值
	private static String getShowValue(String fieldControl,int turn ){
		String result = "inherit";
		char flag = fieldControl.charAt(turn);
		
		switch (flag) {
		case 'N': result="none";
			      break;
		default:
			break;
		}
		return result;
	}
	//--通过functionControl 和字段的序号 得到display的值
	private static boolean getFunValue(String functionControl,int turn ){
		boolean result = true;
		char flag = functionControl.charAt(turn);
		
		switch (flag) {
		case '0': result=false;
			      break;
		default:
			break;
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public String getFormPageByObjs(ServletContext servletContext,String appId,String activityName,Map<String,Object> value){
		Configuration configuration = new Configuration();
		configuration.setObjectWrapper(new DefaultObjectWrapper());
		configuration.setServletContextForTemplateLoading(servletContext, "");
		configuration.setEncoding(Locale.CHINA, "UTF-8");
		ApplicationService applicationService  = (ApplicationService) BeanFactory.getBean("applicationService");
		Application application = applicationService.get(appId);
		Form form = application.getForm();
		
		Template temp;
		try {
			temp =configuration.getTemplate(form.getTempletPath());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "模板文件不存在或路径错误！";
		}
		FieldService fieldService = (FieldService) BeanFactory.getBean("fieldService");
		List<Field> fields = fieldService.getFieldsByformId(form.getFormId());
		Object[] objs = new Object[]{appId,application.getFlowId(),activityName,form.getFormId()};
		ControlService controlService = (ControlService) BeanFactory.getBean("controlService");
		Control control = controlService.getControlByObjects(objs);
		Map root = new HashMap();
		for (int i = 0; i < fields.size() ;i++){
			Field field = fields.get(i);
			Map atts = new HashMap();
			root.put(field.getFieldName(),atts);
			if(getReadValue(control.getFieldControl(),i))
			atts.put("readonly", "");
			atts.put("show", getShowValue(control.getFieldControl(),i));
			if(value!=null&&value.size()!=0&&value.get(field.getFieldName())!=null){
				atts.put("value",value.get(field.getFieldName()) );
			}
		}
	    
		//--操作的种类改成动态的
		if(getFunValue(control.getFunctionControl(),0))
		root.put("save","" );
		if(getFunValue(control.getFunctionControl(),1))
			root.put("submit","" );
		if(getFunValue(control.getFunctionControl(),2))
			root.put("close","" );
		Writer out = new StringWriter();
		try {
			temp.process(root, out);
			out.flush();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return out.toString();
	}
	public Form getById(String formId){
		return formDao.get(formId);
	}
	
	@Transactional(readOnly = false)
	public void saveOrUpdate(Form form) {
		formDao.saveOrUpdate(form);
	}
	
	/**
	 * 装配表单
	 * 
	 * @param appId
	 * @param workId
	 * @param activity
	 * @param userId
	 * @return
	 */
	public FormUI assembleForm(String appId, String workId, String activity, String userId, boolean isMobile) {

		Application app = this.appDao.get(appId);

		AppHandle handle = app.getHandle();

		String javaClass = handle.getHandleJava();

		Object obj = ObjectUtils.getInstance(javaClass);

		if (obj == null) {

		} else {
			FormHandle assembler = (FormHandle) obj;
//			log.info("\n组装web端表单开始.....\n");
			Map<String, Object> context = new HashMap<String, Object>();
			if (isMobile) {
				context.put("isMobile", true);
				context.put("userId", userId);
			}
			context.put("canAutoDelete", "true");
			return assembler.assemble(app, workId, activity, userId, context);
		}
		return null;
	}
}
